import 'package:blurb/common/routers/names.dart';
import 'package:blurb/common/values/images.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:blurb/common/models/user.dart';

class SettingsPage extends StatelessWidget {
  const SettingsPage({super.key});

  @override
  Widget build(BuildContext context) {
    final userStore = Provider.of<UserStore>(context);
    
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Observer(
          builder: (_) {
            final User? currentUser = userStore.currentUser;
            
            return Column(
              children: [
                _buildHeader(context),
                _buildProfileSection(context, currentUser),
                _buildSettingsItems(context),
                const Spacer(),
                _buildLogoutButton(context),
              ],
            );
          }
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.0.w, vertical: 16.0.h),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 居中标题
          Center(
            child: Text(
              'set up',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 24.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          // 左侧返回按钮
          Positioned(
            left: 0,
            child: GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: Colors.white,
                size: 24.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProfileSection(BuildContext context, User? user) {
    // 使用默认头像，如果用户未登录或没有头像
    final avatar = user?.avatar ?? MIP.avatar;
    
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 20.0.h),
      child: GestureDetector(
        onTap: () {
          GoRouter.of(context).push(RNS.information);
        },
        child: ListTile(
          leading: CircleAvatar(
            radius: 25.r,
            backgroundImage: avatar.startsWith('assets/') 
                ? AssetImage(avatar) as ImageProvider
                : NetworkImage(avatar),
          ),
          title: Text(
            user?.nickname ?? '',
            style: GoogleFonts.racingSansOne(
              color: Colors.white,
              fontSize: 16.sp,
            ),
          ),
          trailing: Icon(
            Icons.arrow_forward_ios,
            color: Colors.white,
            size: 20.sp,
          ),
        ),
      ),
    );
  }

  Widget _buildSettingsItems(BuildContext context) {
    return Column(
      children: [
        _buildSettingItem(
          title: 'Privacy Policy',
          onTap: () {
            // 跳转到隐私政策页面
          },
        ),
        _buildSettingItem(
          title: 'Terms Of Service',
          onTap: () {
            // 跳转到服务条款页面
          },
        ),
        _buildSettingItem(
          title: 'Eula',
          onTap: () {
            // 跳转到Eula页面
          },
        ),
        _buildSettingItem(
          title: 'Delete account',
          onTap: () {
            // 显示删除账户确认对话框
            _showDeleteAccountDialog(context);
          },
        ),
      ],
    );
  }

  Widget _buildSettingItem({
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
        child: Row(
          children: [
            Text(
              title,
              style: GoogleFonts.inter(color: Colors.white, fontSize: 16.sp),
            ),
            const Spacer(),
            Icon(Icons.arrow_forward_ios, color: Colors.white, size: 20.sp),
          ],
        ),
      ),
    );
  }

  // 显示删除账户确认对话框
  void _showDeleteAccountDialog(BuildContext context) {
    final userStore = Provider.of<UserStore>(context, listen: false);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text(
          'Delete Account',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        content: Text(
          'Are you sure you want to delete your account? This action cannot be undone.',
          style: GoogleFonts.inter(
            color: Colors.white70,
            fontSize: 16.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.inter(
                color: Colors.white70,
                fontSize: 16.sp,
              ),
            ),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context); // 关闭对话框
              
              // 执行删除账户操作
              final success = await userStore.deleteAccount();
              
              if (success && context.mounted) {
                // 删除成功后跳转到登录引导页
                context.go(RNS.guide);
              }
            },
            child: Text(
              'confirm',
              style: GoogleFonts.racingSansOne(
                color: Color(0xFF60C3FF),
                fontSize: 20.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLogoutButton(BuildContext context) {
    final userStore = Provider.of<UserStore>(context);
    return Padding(
      padding: EdgeInsets.all(30.0.w),
      child: GestureDetector(
        onTap: () async {
          // 处理退出登录
          await userStore.logout();
          Fluttertoast.showToast(
            msg: "Logged out successfully",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            backgroundColor: Colors.green,
            textColor: Colors.white,
          );
          if (context.mounted) {
            context.go(RNS.guide);
          }
        },
        child: Container(
          width: double.infinity,
          height: 56.h,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment(0.50, 0.00),
              end: Alignment(0.50, 0.96),
              colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
            ),
            borderRadius: BorderRadius.circular(30.r),
          ),
          child: Center(
            child: Text(
              'Log out',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
